package com.fubowen.lepton.helper

import android.content.Intent
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import java.io.File

object IntentHelper {

    fun Fragment.shareFile(title: String, filePath: String) {

        val file = File(filePath)
        val url = FileProvider.getUriForFile(
            this.requireContext(),
            "com.fubowen.lepton.fileprovider",
            file
        )
        val intent = Intent().apply {
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_STREAM, url)
            type = "*/*"
        }
        val chooser = Intent.createChooser(intent, title)
        kotlin.runCatching {
            startActivity(chooser)
        }
    }

    fun Fragment.shareSite(title: String?, url: String?) {
        val share = Intent.createChooser(Intent().apply {
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_TEXT, "${title}\n${url}")
            putExtra(Intent.EXTRA_TITLE, title)
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            type = "text/plain"
        }, title)
        kotlin.runCatching {
            startActivity(share)
        }
    }
}